<template>
    <div class="app-container">
        <!-- <el-button @click="ceshi">测试</el-button> -->
        <!-- 搜索模块 -->
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="文件名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="文件名称" size="small" style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="所属项目" prop="approval_id">
                <el-select v-model="queryParams.approval_id" placeholder="所属项目" size="small" style="width: 240px">
                    <el-option v-for="dict in processOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue">
                        <span style="float: left">{{ dict.dictLabel }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictLabelName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属模板" prop="budget_id">
                <el-select v-model="queryParams.budget_id" placeholder="所属模板" size="small" style="width: 240px">
                    <el-option v-for="dict in codeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue">
                        <span style="float: left">{{ dict.dictLabel }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictLabelName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="使用场景" prop="scene">
                <el-select v-model="queryParams.scene" placeholder="使用场景" size="small" style="width: 240px">
                    <el-option v-for="dict in sceneOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 图标权限模块 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['admin:budget:enter:addenter:post']" type="primary" plain icon="el-icon-upload"
                    size="mini" @click="handleFileAdd">Excel录入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['admin:budget:form:add:post']" type="primary" plain icon="el-icon-plus" size="mini"
                    @click="handleAdd">系统录入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['admin:budget:form:delete:{id}:get']" type="danger" plain icon="el-icon-delete"
                    size="mini" :disabled="multiple" @click="handleDelete">批量删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:clearsavefile:download:post']" type="warning" plain icon="el-icon-download"
                    size="mini" :disabled="multiple" @click="handleDownload">批量导出</el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
        </el-row>
        <!-- 展示模块 -->
        <el-table v-loading="loading" :data="formworkList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="文件名称" align="center" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <router-link
                        :to="hasPermi(['admin:budget:form:model:list:post']) ? '/budget/channel/data/' + scope.row.id + '/' + scope.row.budget_id : '#'"
                        class="link-type">
                        <span>{{ scope.row.name }}</span>
                    </router-link>
                </template>
            </el-table-column>
            <el-table-column label="所属项目" align="center" prop="approval_id" :formatter="approvalFormat" />
            <el-table-column label="所属模板" align="center" prop="budget_id" :formatter="modelFormat" />
            <el-table-column label="使用场景" align="center" prop="scene" :formatter="sceneFormat" />
            <el-table-column v-if="hasPermi(['system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:get'])"
                label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-hasPermi="['system:clearsavefile:download:post']" size="mini" type="text"
                        icon="el-icon-download" @click="handleDownload(scope.row)">下载
                    </el-button>
                    <el-button v-hasPermi="['admin:budget:form:delete:{id}:get']" size="mini" type="text"
                        icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        <!-- 新增 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="文件名称" prop="name">
                    <el-input v-model="form.name" placeholder="文件名称" />
                </el-form-item>
                <el-form-item label="所属项目" prop="approval_id">
                    <el-select v-model="form.approval_id" placeholder="所属项目" clearable style="width: 100%;">
                        <el-option v-for="dict in processOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue">
                            <span style="float: left">{{ dict.dictLabel }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictLabelName }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属年度" prop="yearly">
                    <el-input v-model.number="form.yearly" placeholder="所属年度" />
                </el-form-item>
                <el-form-item label="所属模板" prop="budget_id">
                    <el-select v-model="form.budget_id" placeholder="所属模板" clearable style="width: 100%;">
                        <el-option v-for="dict in codeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue">
                            <span style="float: left">{{ dict.dictLabel }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictLabelName }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件导入" prop="path" v-if="!this.bolSysOrExcel">
                    <el-upload class="upload-demo" drag ref="uploadRef" :http-request="chunkUpload" :action="uploadUrl"
                        :data="uploadData" :on-success="handleSuccess" :on-error="onError" name="file" :headers="headers"
                        accept=".xlsx, .xls, .csv">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">
                            <p>只能上传xls/xlsx/csv文件，且列名不能重复</p>
                            <p>请确保上传文件与模板文件格式一致</p>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import { modelToDict } from "@/api/vadmin/budget/formwork/formworkapi";
import { listType, addType, modelEqualFile, delType, downloadType } from "@/api/vadmin/budget/channel/channelapi";
import { processType, ceshiType } from "@/api/vadmin/process/approval/index";
import chunkUpload from "@/utils/chunkUpload";
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
    name: "Channel",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组---ID数据
            ids: [],
            valNames: [],
            // 选中数据---全部数据
            rows: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 显示搜索条件
            showSearch: true,
            // 查询参数
            queryParams: {
                pageNum: 1, // 当前页数
                pageSize: 10, // 每页显示几个
                name: undefined,
                budget_id: undefined,
                scene: undefined,
                approval_id: undefined
            },
            // 日期范围
            dateRange: [],
            // 表单参数
            form: {},
            // 状态数据字典
            statusOptions: [],
            // 场景数据字典
            sceneOptions: [],
            // 模板数据
            codeOptions: [],
            // 模板数据
            processOptions: [],
            // 模板表格数据
            formworkList: [],
            rules: {
                name: [
                    { required: true, message: "文件名称不能为空", trigger: "blur" }
                ],
                yearly: [
                    { required: true, message: "所属年度不能为空", trigger: "blur" }
                ],
                // approval_id: [
                //     { required: true, message: "所属项目不能为空", trigger: "blur" }
                // ],
                budget_id: [
                    { required: true, message: "所属模板不能为空", trigger: "blur" }
                ],
                path: [
                    { required: true, validator: this.validatorPath(), trigger: "blur" }
                ]
            },
            // 文件上传
            chunkUpload: chunkUpload, // 文件上传
            uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', // 文件上传的路径
            uploadData: {},
            headers: {
                Authorization: "Bearer " + getToken()
            },
            // 判断是系统录入还是Excel录入 true:系统录入 false Excel录入
            bolSysOrExcel: true
        };
    },
    created() {
        // 状态字典查询
        this.getDicts("sys_normal_disable").then(response => {
            this.statusOptions = response.data;
        });
        // 场景字典查询
        this.getDicts("explorate_type").then(response => {
            this.sceneOptions = response.data;
        });
        // 模板数据查询
        this.getformData()
        // 初始化系统录入列表
        this.getList();
        // 项目数据查询
        this.getProcessData()
    },
    methods: {
        ceshi() {
            ceshiType().then(response => { })
        },
        validatorPath() {
            return (rule, value, callback) => {
                if (!this.bolSysOrExcel && !value) {
                    return callback(new Error("模板文件不能为空"));
                } else {
                    callback();
                }
            }
        },

        // ============================================= 字典翻译 ===================================

        // 数据状态字典翻译
        approvalFormat(row, column) {
            return this.selectDictLabel(this.processOptions, row.approval_id);
        },
        // 场景字典翻译
        sceneFormat(row, column) {
            return this.selectDictLabel(this.sceneOptions, row.scene);
        },
        // 模板字典翻译
        modelFormat(row, column) {
            return this.selectDictLabel(this.codeOptions, row.budget_id);
        },
        // ============================================= 表头条件查询 ===================================

        // 查询模板数据【转字典】
        getformData() {
            modelToDict().then(response => {
                this.codeOptions = JSON.parse(Decrypt(response.data))
            });
        },
        // 查询项目数据【转字典】
        getProcessData() {
            processType().then(response => {
                this.processOptions = response.data
            })
        },

        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                name: undefined,
                yearly: undefined,
                approval_id: undefined,
                budget_id: undefined,
                path: undefined,
            };
            this.resetForm("form");
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
            this.$refs.uploadRef.clearFiles()
        },

        // ============================================= 按钮操作 ===================================

        /** 数据录入 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.bolSysOrExcel = true;
            this.title = "系统数据录入";
        },
        /** 文件上传录入 */
        handleFileAdd() {
            this.reset();
            this.open = true;
            this.bolSysOrExcel = false;
            this.title = "Excel数据录入";
        },
        // 删除
        handleDelete(row) {
            const ids = row.id || this.ids;
            const names = row.name || this.valNames
            this.$confirm('是否确认删除文件编码为"' + names + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delType({ 'id': ids });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            });
        },

        /** 文件下载 **/
        handleDownload(row) {
            const rows = row.id ? [row] : this.rows
            downloadType({ "fileData": rows }).then((response) => {
                var files = JSON.parse(Decrypt(response.data)).files
                files.forEach(item => {
                    this.download(item.path, item.name);
                });
            })
        },

        // ============================================= 数据展示Table表单 ===================================

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.valNames = selection.map(item => item.name);
            this.rows = selection.map(item => item);
            this.single = selection.length !== 1;
            this.multiple = selection.length < 2;
        },

        /** 查询模板文件列表 */
        getList() {
            this.loading = true;
            listType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                var resData = JSON.parse(Decrypt(response.data))
                this.formworkList = resData.results;
                this.total = resData.count;
                this.loading = false;
            });
        },

        // ============================================= 弹框操作 ===================================

        // 系统 - 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        /** 系统-提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    addType(this.form).then(response => {
                        this.msgSuccess(response.msg);
                        this.open = false;
                        this.getList();
                        this.form.path = undefined
                    });
                }
            });
        },
        // ============================================= 文件上传 ===================================
        handleSuccess(data) {
            if (this.form.budget_id == undefined) {
                this.$message.error('请先选择模板文件！');
                return false
            }
            modelEqualFile({ 'path': data.saveFile, 'budget_id': this.form.budget_id }).then(response => {
                var resData = JSON.parse(Decrypt(response.data))
                if (resData.bol) {
                    this.form.path = data.saveFile
                    this.$message.success('文件上传成功！');
                    this.$refs.uploadRef.clearFiles()
                } else {
                    this.onInspect()
                }
            })

        },
        onError() {
            this.form.path = undefined
            this.$message.error('文件上传失败！');
            this.$refs.uploadRef.clearFiles()
        },
        onInspect() {
            this.form.path = undefined
            this.$message.error('上传文件与模板文件不一致！');
            this.$refs.uploadRef.clearFiles()
        }
    }
};
</script>